package xkp.lesson6;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        CopyOnWriteArrayList<Socket> sockets = new CopyOnWriteArrayList<>();
        //等待连接
        new Thread(){
            @Override
            public void run() {
                try {
                    while(true) {
                        Socket socket = serverSocket.accept();
                        System.out.println(socket.getRemoteSocketAddress() + "连接成功");
                        sockets.add(socket);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        //把主线程留下来给所有的客户端发消息用
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.println("请输入控制命令...");
            //给所有客户端发的命令
            String cmd = scanner.nextLine();
            sendToAll(cmd,sockets);
        }
    }

    private static void sendToAll(String cmd, CopyOnWriteArrayList<Socket> sockets) throws IOException {
        for(Socket socket:sockets){
            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.writeUTF(cmd);
            dataOutputStream.flush();
            //此处不要关闭dataOutputStream，关闭会造成socket关闭
        }
    }
}
